import {Utils} from "./utils";

declare const wx: any;

export class GameData {
  myScore: number = -1;
  maxScore: number = -1;
  openid: string = '';
  rankList: Array<any>;

  async init() {
    this.rankList = await Utils.getScoreInfo();
    this.maxScore = await Utils.getMyMax();
  }

  postScore(score, openid) {
    this.myScore = score;
    if (score > this.maxScore) {
      this.maxScore = score;
      wx.setUserCloudStorage({
        KVDataList: [{key: 'score', value: '' + this.maxScore}],
      });
      this.refresh(score, openid);
    }
  }

  refresh(score, openid) {
    for (let i = 0; i < this.rankList.length; i++) {
      const itemData = this.rankList[i];
      if (itemData.openid === openid) {
        itemData.KVDataList[0].value = score.toString();
        break;
      }
    }
    this.rankList.sort((a, b) => {
      return parseInt(a.KVDataList[0].value) - parseInt(b.KVDataList[0].value);
    });
  }
}

export const gameData = new GameData();